package com.exposit.zbs.controller;

import com.exposit.zbs.model.*;
import com.exposit.zbs.service.IGrantApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;


@Controller
@RequestMapping("/grant")
public class GrantController {

	@Autowired
	private IGrantApplicationService grantService;

	@RequestMapping(value = {"/create"}, method = {RequestMethod.GET})
	public String create(HttpSession session, Model model) {

		model.addAttribute("grant", new GrantApplication());
		model.addAttribute("grantAreas", grantService.getAllAreas());
		return "grantCreation";
	}

	@RequestMapping(value = "/create", method = {RequestMethod.POST})
	public ModelAndView create(GrantApplication grant, Long grantAreaId, HttpSession session) { // TODO Validate fields!!!!!
		User user = (User) session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView();
		if (user != null && grant != null && grantAreaId != null) {
			grant.setCreationDate(new java.util.Date());
			grant.setUser(user);
			grant.setGrantArea(grantService.getGrantAreaById(grantAreaId));
			grantService.saveGrant(grant);

			mav = new ModelAndView("redirect:/");
			mav.addObject("message", "You have sent a new application.");

			return mav;
		} else {

			mav.addObject("error", "You should be logged in");
			mav.setViewName("login");
			return mav;
		}
	}

	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public ModelAndView viewAll(HttpSession session) {

		return null;
	}

	@RequestMapping(value = "/view/{grantId}", method = RequestMethod.GET)
	public ModelAndView viewSingle(@PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, HttpSession session, String delMessage) {

		ModelAndView mav = new ModelAndView("grant.viewSingle");
		if (delMessage != null) {
			mav.addObject("delMessage", delMessage);
		}
		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User && userObject != null) {
			User currentUser = (User) userObject;
			if (currentUser.getRole().getRoleName().equals("ROLE_ADMIN")) {
				BigDecimal areaMoneyAmount = grantService.getAvailMoneyForArea(grantApplication.getGrantArea().getGrantAreaId());
				mav.addObject("areaMoneyAmount", areaMoneyAmount);

			}
		}
		mav.addObject("requestedGrant", grantApplication);
		return mav;
	}

	@RequestMapping(value = "/view/{grantId}", method = RequestMethod.POST)
	public ModelAndView getComment(String commentText, @PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, HttpSession session) {

		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User && userObject != null && !commentText.equals(null) && !commentText.equals("")) {
			User currentUser = (User) userObject;
			Comment comment = new Comment(commentText, currentUser, grantApplication);
			comment.setCommentDate(new java.util.Date());
			grantService.saveComment(comment);
		}
		ModelAndView mav = new ModelAndView("grant.viewSingle");
		GrantApplication updatedGrant = grantService.getGrantById(new Long(grantId));
		mav.addObject("requestedGrant", updatedGrant);
		return mav;
	}

	@RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.GET)
	public ModelAndView delComment(@PathVariable String commentId, HttpSession session) {

		ModelAndView mav = new ModelAndView();
		Comment comment = grantService.getCommentById(Long.parseLong(commentId));
		GrantApplication grant = comment.getGrantApplication();
		Long grantId = grant.getGrantId();
		Object user = session.getAttribute("sessionUser");
		if (user instanceof User && user != null && ((User) user).getRole().getRoleName().equals("ROLE_ADMIN")) {
			grantService.deleteComment(comment);
			mav.setViewName("redirect:/grant/view/" + grantId);
			mav.addObject("delMessage", "Comment was deleted");
			return mav;
		}
		mav.setViewName("redirect:/grant/view/" + grantId);
		return mav;
	}

	@RequestMapping(value = "/like/{grantId}", method = RequestMethod.GET)
	@ResponseBody
	public Like like(@PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, HttpSession session) {

		Object userObject = session.getAttribute("sessionUser");
		if (userObject instanceof User) {
			User currentUser = (User) userObject;
			Like like = grantApplication.isLikedByLogin(currentUser.getUserLogin());
			if (like == null) {
				grantService.saveLike(new Like(grantApplication, currentUser));
			} else {
				grantService.removeLike(like);
			}
		}
		return null;
	}

	@RequestMapping(value = "/writeChangelog", method = RequestMethod.POST)
	public ModelAndView saveChangelogRecord(String grantId, String changelogText, HttpSession session) {

		ModelAndView mav = new ModelAndView("redirect:/grant/view/" + grantId.toString());
		Object userObject = session.getAttribute("sessionUser");
		if (!changelogText.isEmpty() && userObject instanceof User) {
			User currentUser = (User) userObject;
			if (!grantId.isEmpty()) {
				GrantApplication ga = grantService.getGrantById(new Long(grantId));
				GrantChangelog clRecord = new GrantChangelog(ga, changelogText, new Date());
				grantService.saveChangeLogRecord(clRecord);
			}
		}
		return mav;
	}

	@RequestMapping(value = {"/edit/{grantId}"}, method = {RequestMethod.GET})
	public String edit(@PathVariable Long grantId, @PathVariable("grantId") GrantApplication grant, HttpSession session, Model model) {

		model.addAttribute("grant", grant);
		return "grant.edit";
	}

	@RequestMapping(value = "/edit/{grantId}", method = {RequestMethod.POST})
	public ModelAndView edit(@PathVariable Long grantId, @PathVariable("grantId") final GrantApplication originalGrant, GrantApplication grant, HttpSession session) { // TODO Validate fields!!!!!

		User user = (User) session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView();

		if (user != null && grant != null) {
			grant.setGrantId(grantId);
			grant.setGrantApplicationStatus(originalGrant.getGrantApplicationStatus());
			grant.setReviewDate(originalGrant.getReviewDate());
			grantService.updateGrant(grant);
			mav = new ModelAndView("redirect:/");
			mav.addObject("message", "You have edit application.");
			return mav;
		} else {

			mav.addObject("error", "You should be logged in");
			mav.setViewName("login");
			return mav;
		}
	}

	@RequestMapping(value = "/delete/{grantId}", method = RequestMethod.GET)
	public ModelAndView delete(@PathVariable("grantId") final GrantApplication grant, HttpSession session) {

		Object currentUserObject = session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView();
		if (currentUserObject != null && currentUserObject instanceof User) {
			User currentUser = (User) currentUserObject;
			User grantUser = grantService.getUserByGrant(grant);
			if (currentUser.getRole().getRoleName().equals("ROLE_ADMIN")) {
				grantService.removeGrant(grant.getGrantId());
				mav.setViewName("redirect:/area/{grantAreaLink}");
				mav.addObject("delMessage", "Grant was deleted successfuly");
			} else {
				mav.setViewName("redirect:/");
				mav.addObject("errMessage", "You should be owner");
			}
		} else {
			mav.setViewName("redirect:/");
			mav.addObject("errMessage", "You should be logged in");
		}
		return mav;

	}

	@RequestMapping(value = "/finish/{grantId}", method = RequestMethod.GET)
	public ModelAndView finish(@PathVariable("grantId") final GrantApplication grant, HttpSession session) {

		Object currentUserObject = session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView("redirect:/area/" + grant.getGrantArea().getLink());
		if (currentUserObject != null && currentUserObject instanceof User) {
			User currentUser = (User) currentUserObject;
			if (currentUser.getUserId().equals(grant.getUser().getUserId())) {
				grant.setGrantApplicationStatus(new GrantApplicationStatus(4l, "ENDED"));
				grantService.updateGrant(grant);

			}
		}

		return mav;
	}

}
